package org.qiyu.live.account.provider.service.impl;

import jakarta.annotation.Resource;
import org.idea.qiyu.live.framework.redis.starter.key.AccountProviderCacheKeyBuilder;
import org.qiyu.live.account.provider.service.IAccountTokenService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-04
 * Time: 11:05
 */
@Service
public class AccountTokenServiceImpl implements IAccountTokenService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private AccountProviderCacheKeyBuilder cacheKeyBuilder;

    @Override
    public String createAndSaveLoginToken(Long userId) {
        // 1. 生成token
        String token = UUID.randomUUID().toString();
        // 2. redis的key
        String key = cacheKeyBuilder.buildUserInfoKey(token);
        redisTemplate.opsForValue().set(key, userId.toString(), 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getUserIdByToken(String token) {
        String redisKey = cacheKeyBuilder.buildUserInfoKey(token);
        Integer userId = (Integer) redisTemplate.opsForValue().get(redisKey);
        return userId == null ? null : Long.valueOf(userId);
    }
}